(function($, f) {
    var Unslider = function() {
        //  Object clone
        var _ = this;

        //  Set some options
        _.o = {
            speed: 500,     // animation speed, false for no transition (integer or boolean)
            delay: 3000,    // delay between slides, false for no autoplay (integer or boolean)
            init: 0,        // init delay, false for no delay (integer or boolean)
            pause: !f,      // pause on hover (boolean)
            loop: !f,       // infinitely looping (boolean)
            keys: f,        // keyboard shortcuts (boolean)
            dots: f,        // display ••••o• pagination (boolean)
            arrows: f,      // display prev/next arrows (boolean)
            title:f,
            prev: '←',      // text or html inside prev button (string)
            next: '→',      // same as for prev option
            fluid: f,       // is it a percentage width? (boolean)
            starting: f,    // invoke before animation (function with argument)
            complete: f,    // invoke after animation (function with argument)
            items: '>ul',   // slides container selector
            item: '>li',    // slidable items selector
            easing: 'swing',// easing function to use for animation
            autoplay: true,  // enable autoplay on initialisation
            dotsItems:''
        };

        _.init = function(el, o) {
            //  Check whether we're passing any options in to Unslider
            _.o = $.extend(_.o, o);

            _.el = el;
            _.ul = el.find(_.o.items);
            _.max = [el.outerWidth() | 0, el.outerHeight() | 0];
            _.li = _.ul.find(_.o.item).each(function() {
                var me = $(this),
                    width = me.outerWidth(),
                    height = me.outerHeight();

                //  Set the max values
                if (width > _.max[0]) _.max[0] = width;
                if (height > _.max[1]) _.max[1] = height;
            });


            //  Cached vars
            var o = _.o,
                ul = _.ul,
                li = _.li,
                len = li.length;

            //  Current indeed
            _.i = 0;

            //  Set the main element
            el.css({width: _.max[0] + "px",height: _.max[1] + "px", overflow: 'hidden'});

            //  Set the relative widths
            ul.css({position: 'relative', left: 0, width: (len * 100) + '%'});
            li.css({'float': 'left', width: (_.max[0]) + 'px'});

            //  Autoslide
            o.autoplay && setTimeout(function() {
                if (o.delay | 0) {
                    _.play();

                    if (o.pause) {
                        el.on('mouseover mouseout', function(e) {
                            _.stop();
                            e.type == 'mouseout' && _.play();
                        });
                    };
                };
            }, o.init | 0);

            //  Keypresses
            if (o.keys) {
                $(document).keydown(function(e) {
                    var key = e.which;

                    if (key == 37)
                        _.prev(); // Left
                    else if (key == 39)
                        _.next(); // Right
                    else if (key == 27)
                        _.stop(); // Esc
                });
            };
            if('' !== o.dotsItems){
                _.$dots=$(o.dotsItems);
                _.$dots.hover(function(){
                    var $t = $(this);
                    _.stop().to(_.$dots.index($t));
                },function(){
                    o.autoplay && _.play();
                });
            }

            //  Dot pagination
            o.dots && nav('dot');

            //  Arrows support
            o.arrows && nav('arrow');

            o.title && nav('title');

            //  Patch for fluid-width sliders. Screw those guys.
            if (o.fluid) {
                $(window).resize(function() {
                    _.r && clearTimeout(_.r);

                    _.r = setTimeout(function() {
                        var styl = {height: li.eq(_.i).outerHeight()},
                            width = el.outerWidth();

                        ul.css(styl);
                        styl['width'] = Math.min(Math.round((width / el.parent().width()) * 100), 100) + '%';
                        el.css(styl);
                    }, 50);
                }).resize();
            };

            //  Swipe support
            if ($.event.special['swipe'] || $.Event('swipe')) {
                el.on('swipeleft swiperight swipeLeft swipeRight', function(e) {
                    e.type.toLowerCase() == 'swipeleft' ? _.next() : _.prev();
                });
            };

            return _;
        };
        _.to = function(index, callback) {
            if (_.t) {
                _.stop();
                _.play();
            }
            var o = _.o,
                el = _.el,
                ul = _.ul,
                li = _.li,
                current = _.i,
                target = li.eq(index);

            $.isFunction(o.starting) && !callback && o.starting(el, li.eq(current));
            if ((!target.length || index < 0) && o.loop == f) return;
            if (!target.length) index = 0;
            if (index < 0) index = li.length - 1;
            target = li.eq(index);

            var speed = callback ? 5 : o.speed | 0,
                easing = o.easing,
                obj = {height: target.outerHeight()};
            if(_.$dots && _.$dots.length){
                var $dot = _.$dots.eq(index);
                $dot.addClass('on');
                _.$dots.not($dot).removeClass('on');
            }
            if (!ul.queue('fx').length) {
                el.find('.dot').eq(index).addClass('active').siblings().removeClass('active');
                el.find('.title').eq(index).addClass('active').siblings().removeClass('active');

                el.animate(obj, speed, easing) && ul.animate($.extend({left: '-' + index + '00%'}, obj), speed, easing, function(data) {
                    _.i = index;
                    $.isFunction(o.complete) && !callback && o.complete(el, target);
                });
            };
        };
        _.play = function() {
            _.t = setInterval(function() {
                _.to(_.i + 1);
            }, _.o.delay | 0);
        };
        _.stop = function() {
            _.t = clearInterval(_.t);
            return _;
        };
        _.next = function() {
            return _.stop().to(_.i + 1);
        };

        _.prev = function() {
            return _.stop().to(_.i - 1);
        };
        function nav(name, html) {
            switch(name){
                case 'dot':
                    html = '<ol class="dots">';
                    $.each(_.li, function(index) {
                        html += '<li class="' + (index == _.i ? name + ' active' : name) + '">' + ++index + '</li>';
                    });
                    html += '</ol>';
                    break;
                case 'arrow':
                    html = '<div class="';
                    html = html + name + 's">' + html + name + ' prev">' + _.o.prev + '</div>'
                        + html + name + ' next">' + _.o.next + '</div></div>';
                    break;
                case 'title':
                    html='<ol class="sTitle">';
                    $.each(_.li,function(index){
                        html+='<li class="'+ (index == _.i ? name + ' active' : name) +'">'+$(this).data('title')+'</li> '
                    });
                    html+='</ol>';
                    break;
            }
            _.el.addClass('has-' + name + 's').append(html).find('.' + name).click(function() {
                var me = $(this);
                me.hasClass('dot') ? _.stop().to(me.index()) : me.hasClass('prev') ? _.prev() : _.next();
            });
        };
    };
    $.fn.unslider = function(o) {
        var len = this.length;
        return this.each(function(index) {
            var me = $(this),
                key = 'unslider' + (len > 1 ? '-' + ++index : ''),
                instance = (new Unslider).init(me, o);
            me.data(key, instance).data('key', key);
        });
    };

    Unslider.version = "1.0.0";
})(jQuery, false);